package com.wjj.sixinone.handler;


import com.wjj.sixinone.common.exception.GlobalException;
import com.wjj.sixinone.common.pojo.log.ExceptionLogs;
import com.wjj.sixinone.common.util.AuthContextUtil;
import com.wjj.sixinone.common.util.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;

import static com.wjj.sixinone.common.util.CurrentIpUtils.getUserIP;


@ControllerAdvice
@Slf4j
public class ExceptionController {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 异常处理，记录日志并返回错误信息
     */
    @ExceptionHandler(value = GlobalException.class)
    @ResponseBody
    public Result handleException(GlobalException e) {
        saveExceptionLog(e);
        e.printStackTrace();
        return Result.error(e.getStatus(), e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handleException(Exception e) {
        saveExceptionLog(e);
        e.printStackTrace();

        return Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统内部错误"+e.getMessage());
    }


    /**
     * 保存异常日志到 MongoDB
     */


    private void saveExceptionLog(Exception  e) {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        ExceptionLogs logEntry = new ExceptionLogs();
        logEntry.setExceptionMessage(e.getMessage());
        logEntry.setIp(getUserIP());
        logEntry.setMethod(request.getMethod());
        logEntry.setRequestUrl(request.getRequestURI());
        logEntry.setCreateTime(LocalDateTime.now());
        String username = AuthContextUtil.get().getUsername();

        logEntry.setUsername(username);
        if(e instanceof GlobalException){
            logEntry.setCode(((GlobalException) e).getStatus());
        }else {
            logEntry.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        try {
            mongoTemplate.save(logEntry);
        } catch (Exception ex) {
            log.error("Failed to save exception log", ex);
        }
    }
}
